package com.qmth.gkwb.data.security;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.qmth.gkwb.data.document.Student;
import com.qmth.gkwb.data.entity.StudentUser;
import com.qmth.gkwb.data.repository.StudentRepo;
import com.qmth.gkwb.data.repository.StudentUserRepo;

@Service
public class UserService {

	@Autowired private StudentUserRepo studentUserRepo;
	@Autowired private StudentRepo studentRepo;
	
	/**
	 * 用户id可以是报名号或身份证号
	 * 如果长度大于15位，先从主数据库查找，如果查询不到再从mongodb查
	 * @param userId
	 * @return
	 */
	public StudentUser getStudentUserByUserId(String userId){
		StudentUser user = null;
		if(userId != null && userId.trim().length() > 0){
			
			if(userId.trim().length() < 15){
				user = studentUserRepo.findOne(userId);
			}
			else{
				List<StudentUser> users = studentUserRepo.findByCertino(userId);
				if(users.size() > 0){
					user = users.get(0);
				}
				else{
					List<Student> stus = studentRepo.findByCertino(userId);
					if(stus.size() > 0){
						Student stu = stus.get(0);
						user = new StudentUser();
						user.setUserId(stu.getExamId());
						user.setPassword(stu.getPassword());
						user.setPwdModifyCount(1);
					}
				}
			}
		}
		return user;
	}
	
	@Transactional
	public Student modifyPassword(String userId,String password) throws Exception{
		StudentUser user = studentUserRepo.findOne(userId);
		Integer cnt = null;
		Student stu = null;
		if(StringUtils.isEmpty(password)){
			throw new Exception("密码不能为空");
		}
		else{
			user.setPassword(password);
			cnt = user.getPwdModifyCount();
			if(cnt != null){
				user.setPwdModifyCount(++cnt);
			}
			else{
				user.setPwdModifyCount(1);
			}
			List<Student> stus = studentRepo.findByExamId(userId);
			if(stus.size() > 0){
				stu = stus.get(0);
				stu.setPassword(password);
				studentRepo.save(stu);
			}
			studentUserRepo.save(user);
		}
		return stu;
	}
}
